﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace NumeroHeroOnline
{
    public partial class Form1 : Form
    {
        DateTime start;
        Image personagem;
        Point persoPoint;
        TcpClient client;
        StreamReader reader;
        StreamWriter writer;
        int speedX = 100;
        int speedY = 30;
        double deltaTime;
        bool conectou = false;

        public Form1()
        {
            InitializeComponent();
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
            Start();
        }

        private void Start()
        {
            personagem = new Bitmap("images/bonequinho.jpg");
            persoPoint = new Point(20, 50);

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 40;
            timer.Tick += new EventHandler(Update);
            timer.Enabled = true;
        }

        private void Update(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            deltaTime = (now - start).Milliseconds / 1000.0;
            start = now;

            if (conectou)
            {
                panel1.Enabled = false;
                panel1.Visible = false;
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawImage(personagem, persoPoint);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            label3.Text = e.KeyCode.ToString();

            if (e.KeyCode.Equals(Keys.Up))
            {
                Console.WriteLine("apertei");
                persoPoint.Y += (int)(speedY * deltaTime);
                persoPoint.X += (int)(speedX * deltaTime);
            }
        }

        private void Conectar(object sender, EventArgs e)
        {
            try
            {
                int port = Int32.Parse(textBoxPort.Text);
                client = new TcpClient(textBoxServer.Text, port);

                NetworkStream stream = client.GetStream();
                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);

                Thread thread = new Thread(checkMessage);
                thread.Start(); 
            }
            catch (Exception err)
            {
                MessageBox.Show("Erro : " + err.Message);
            }
        }

        private void checkMessage()
        {
            try
            {
                // faz leitura de uma linha do cliente
                String data = reader.ReadLine();

                while (data != null)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        reactToMessage(data);
                    });

                    // aguarda proximos dados
                    data = reader.ReadLine();
                }

                // Shutdown and end connection
                client.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show("Erro lendo do servidor : " + err.Message);
            }
        }

        private void reactToMessage(string data)
        {
            if (data.Equals("server cheio"))
            {
                MessageBox.Show("Server Cheio","Erro de conexão");
            }

            if (data.Equals("conectou"))
            {
                conectou = true;
            }
        }

        private void OnClosing(object sender, FormClosingEventArgs e)
        {
            if (client.Connected)
            {
                client.Close();
            }
        }
    }
}
